import { allApplicationSettings, enumCategories } from "../core/setting/settings";
import { TextualState } from "../core/textual_state";
import { formatSecondsToTimeAgo } from "../core/utils/utils";

export class SettingState extends TextualState{
  constructor(){
    super('SettingState')
  }

  getStateHeaderTitle(){
    return '设置'
  }

  getMainContentHTML(){
    return `
      <div class="sidebar">
        ${this.getCategoryButtonsHtml()}
        <div class="other">
          <button class="styledButton home">首页</button>
          <button class="styledButton map">编辑器</button>
          <button class="styledButton about">关于游戏</button>

          <div class="versionbar">
            <div class="buildVersion">加载中...</div>
          </div>
        </div>
      </div>

      <div class="categoryContainer">
        ${this.getSettingHtml()}
      </div>
    `
  }

  getCategoryButtonsHtml(){
    return Object.keys(enumCategories)
      .map(key => enumCategories[key])
      .map(category => `
        <button class="styledButton categoryButton" data-category-btn="${category.key
        }">
          ${category.text}
        </button>
      `)
      .join('')
  }

  getSettingHtml(){
    const categoriesHTML = {};

    Object.keys(enumCategories).forEach(key => {
      const catName = enumCategories[key].key
      categoriesHTML[catName] = `<div class="category" data-category="${catName}">`
    })

    for(let i = 0; i < allApplicationSettings.length; i++){
      const setting = allApplicationSettings[i]

      categoriesHTML[setting.categoryId] += setting.getHtml(this.app)
    }

    return Object.keys(categoriesHTML)
      .map(k => categoriesHTML[k] += '</div>')
      .join('')
  }

  renderBuildText(){
    const labelVersion = this.htmlElement.querySelector('.buildVersion')
    // const lastBuildMs = new Date().getTime() - G_BUILD_TIME;
    const lastBuildText = formatSecondsToTimeAgo(G_BUILD_TIME);

    const version = {
      'dev': '开发版本',
      'prod': '正式版本'
    }[G_APP_ENVIRONMENT];

    labelVersion.innerHTML = `
      <span class="version">
        ${G_BUILD_VERSION} @ ${version}
      </span>
      <span class="buildTime">
        于${lastBuildText}编译
      </span>
    `
  }

  onEnter(){
    this.renderBuildText();

    this.handlerButtonCallback();

    this.initSetting();
    this.initCategoryButtons();

    this.htmlElement.querySelector(".category").classList.add("active");
    this.htmlElement.querySelector(".categoryButton").classList.add("active");
  }

  handlerButtonCallback(){
    this.trackClicks(this.htmlElement.querySelector('.about'), this.onAboutClicked, {
      preventDefault: false
    })

    this.trackClicks(this.htmlElement.querySelector('.home'), () => {
      let { ok } = this.dialogs.showInfo('跳转首页', '你是否需要跳转至首页呢？', ['cancel:bad:取消', 'ok:success:是']);
      
      ok.add(() => {
        this.moveToState('MainMenuState')
      })
    })

    let mapButton = this.htmlElement.querySelector('.map');

    if(G_IS_PROD){
      mapButton.classList.add('remove')
    }

    this.trackClicks(mapButton, () => {
      this.moveToState('MapEditorState')
    })
  }

  initSetting(){
    allApplicationSettings.forEach(setting => {
      const element = this.htmlElement.querySelector(`[data-setting="${setting.id}"]`);
      setting.bind(this.app, element, this.dialogs);
      setting.syncValueToElement();
      this.trackClicks(
        element,
        () => {
          setting.modify();
        },
        { preventDefault: false }
      )
    })
  }

  initCategoryButtons(){
    Object.keys(enumCategories).forEach(key => {
      const category = enumCategories[key].key
      const button = this.htmlElement.querySelector(`[data-category-btn="${category}"]`);
      this.trackClicks(
        button,
        () => {
          this.setActiveCategory(category)
        },
        { preventDefault: false }
      )
    })
  }

  setActiveCategory(category){
    const activeCategory = this.htmlElement.querySelector('.category.active')
    const activeCategoryButton = this.htmlElement.querySelector('.categoryButton.active')

    if(activeCategory.getAttribute('data-category') == category){
      return;
    }

    activeCategory.classList.remove('active')
    activeCategoryButton.classList.remove('active')

    const newCategory = this.htmlElement.querySelector(`[data-category="${category}"]`);
    const newCategoryButton = this.htmlElement.querySelector(`[data-category-btn="${category}"]`);

    newCategory.classList.add('active')
    newCategoryButton.classList.add('active')
  }

  onAboutClicked(){
    this.moveToStateAddGoBack('AboutState')
  }
}